<?php
// +----------------------------------------------------------------------
// | [ WE ONLY DO WHAT IS NECESSARY ]
// +----------------------------------------------------------------------
// | Author < 931274989@qq.com >
// +----------------------------------------------------------------------
// | Explain 短信
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\validate\admin\SmsConfig as smsConfigValidate;
use app\validate\admin\Phone as phoneValidate;
use dayu\SignatureHelper;
use think\Db;

class SmsConfig extends Base
{
  public function index()
  {
    $data = Db::name('smsconfig')->where('sms','sms')->find();
    $this->assign('data',$data);
    return $this->fetch();
  }

  public function publish()
  {
    if($this->request->isPost()) {
      $post = $this->request->post();
      (new smsConfigValidate())->goCheck();
      if(false == Db::name('smsconfig')->where('sms','sms')->update($post)) {
        return $this->error('提交失败');
      } else {
        addLog(); //写入日志
        return $this->success('提交成功','smsConfig/index');
      }
    } else {
      return $this->error('非法请求');
    }
  }

  // 发送测试短信
  public function smsto()
  {
    if($this->request->isPost()) {
      $post = $this->request->post();
      (new phoneValidate())->goCheck();

      $phone = (string)$post['phone'];
      
      $code = '1234';

      $smsto = $this->SendSms($code ,$phone);
      if(!empty($smsto)) {
        return $this->error('发送失败');
      } else {
        $phone = hide_phone($phone);
        addLog($phone);//写入日志
        return $this->success('短信发送成功');
      }
    } else {
      return $this->fetch();
    }
  }

  /**
   * 阿里大鱼短信发送
   * @param [type] $appkey    [description]
   * @param [type] $secretKey [description]
   * @param [type] $type      [description]
   * @param [type] $name      [description]
   * @param [type] $param     [description]
   * @param [type] $phone     [description]
   * @param [type] $code      [description]
   * @param [type] $data      [description]
   */
  function SendSms($code,$phone)
  {
    $config = Db::name('smsconfig')->where('sms','=','sms')->find();
    $params = array ();

    //阿里云的AccessKey
    $accessKeyId = $config['appkey'];

    //阿里云的Access Key Secret
    $accessKeySecret = $config['secretkey'];

    //要发送的手机号
    $params["PhoneNumbers"] = $phone;

    //签名，第三步申请得到
    $params["SignName"] = $config['name'];

    //模板code，第三步申请得到
    $params["TemplateCode"] = $config['code'];

    //模板的参数，注意code这个键需要和模板的占位符一致
    $params['TemplateParam'] = Array (
        "code" => $code
    );
    
    // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
    }
    
    // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
    $helper = new SignatureHelper();
    try{
      // 此处可能会抛出异常，注意catch
      $content = $helper->request(
        $accessKeyId,
        $accessKeySecret,
        "dysmsapi.aliyuncs.com",
        array_merge($params, array(
            "RegionId" => "cn-hangzhou",
            "Action" => "SendSms",
            "Version" => "2017-05-25",
        ))
      // fixme 选填: 启用https
      // ,true
      );
      $res=array('errCode'=>0,'msg'=>'ok');
      if($content->Message!='OK'){
        $res['errCode']=1;
        $res['msg']=$content->Message;
      }
      return $this->error($res);
      // echo json_encode($res);
    }catch(\Exception $e){
      return $this->error('短信接口请求错误');
    }

  }

}
